package logicaPersistencia.poolConexiones;


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class PoolConexiones implements IPoolConexiones 
{
	private String driver,user,password,url;
	private int nivelTransaccionalidad;
	private Conexion conexiones[];
	private int tamanio,creadas,tope;
	

	public PoolConexiones() throws FileNotFoundException, IOException, ClassNotFoundException 
	{
		Properties p = new Properties();
		String nomArch = "config/Datos.properties";
		p.load(new FileInputStream (nomArch));

		driver = p.getProperty("driver");
		Class.forName(driver);
		
		url=p.getProperty("url");
		user=p.getProperty("user");
		password =p.getProperty("pass");
		nivelTransaccionalidad = Connection.TRANSACTION_READ_COMMITTED; 
		tamanio=50;
		conexiones = new Conexion[tamanio];
		tope = 0;
		creadas = 0;
	}

	@Override
	public synchronized IConexion obtenerConexion(boolean bool)  throws SQLException, FileNotFoundException, ClassNotFoundException, IOException
	{			
		if(tope == 0) 
		{
			if(creadas == tamanio) 
			{
				try 
				{
					conexiones.wait();
				} 
				catch (InterruptedException e) 
				{
					e.printStackTrace();
				}
			} else {
				conexiones[tope] = getConnection();
				tope++;
				creadas++;
			}
			
		}
		Conexion oConexion = conexiones[tope - 1];
		tope--;
		return oConexion;
		
	}

	@Override
	public void liberarConexion(boolean bool, IConexion conex) 
	{
		synchronized(conexiones) {
			try {
				if(bool) {
					((Conexion) conex).getCon().commit();
				} else {
					((Conexion) conex).getCon().rollback();
				}
				conexiones[tope] = (Conexion) conex;
				tope += 1;
				conexiones.notify();
				
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	private Conexion getConnection() throws FileNotFoundException, IOException, ClassNotFoundException, SQLException 
	{
		Class.forName(driver);
		Connection oConnection = null;
		Conexion conn = null;
		
		oConnection = DriverManager.getConnection(url, user, password);
		oConnection.setAutoCommit(false);
		oConnection.setTransactionIsolation(nivelTransaccionalidad);
		conn = new Conexion(oConnection);
		
		return conn; 
	}
}
